/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.web.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import yhao.infra.common.InfraCommonConstants;
import yhao.infra.common.cache.YhaoCache;
import yhao.infra.web.YhaoInfraWebProperties;
import yhao.infra.web.common.util.CommonWebUtil;
import yhao.infra.web.constants.WebCommonCacheKey;
import yhao.infra.web.constants.WebCommonConstants;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;


/**
 * 访问过滤器
 *
 * @author yoara
 */
public class AccessThresholdFilter implements Filter {
    private static final String IP_CACHE_PREFIX = "micro.access.ip:";
    private static final String SESSION_CACHE_PREFIX = "micro.access.session:";

    private static final Logger logger = LoggerFactory.getLogger(AccessThresholdFilter.class);
    private YhaoCache yhaoCache;
    private YhaoInfraWebProperties properties;
    private int throttlingInterval;
    private int maxAccessCountPerSession;
    private int maxAccessCountPerIP;
    private Set<String> bypassResourceSet = new HashSet<>();

    /**
     * @see Filter#init(FilterConfig)
     */
    @Override
    public void init(FilterConfig filterConfig) {
        ServletContext servletContext = filterConfig.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        yhaoCache = ctx.getBean(InfraCommonConstants.COMMON_CACHE_BEAN_NAME,YhaoCache.class);
        properties = ctx.getBean(YhaoInfraWebProperties.class);

        throttlingInterval = properties.getAccessFilter().getThrottlingInterval();
        maxAccessCountPerSession = properties.getAccessFilter().getMaxAccessCountPerSession();
        maxAccessCountPerIP = properties.getAccessFilter().getMaxAccessCountPerIp();

        String bypassResourceStr = properties.getAccessFilter().getBypassResources();
        if (StringUtils.isNotEmpty(bypassResourceStr)) {
            String[] bypassResources = bypassResourceStr.split(",");
            Collections.addAll(bypassResourceSet, bypassResources);
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
            chain.doFilter(request, response);
            return;
        }
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String urlPath = httpRequest.getServletPath();
        for (String url : bypassResourceSet) {
            if (urlPath.startsWith(url)) {
                chain.doFilter(httpRequest, httpResponse);
                return;
            }
        }
        AccessKey accessKey = this.getAccessKey(httpRequest);

        String ipAddress = accessKey.getRemoteAddr();
        if (checkThreshold(httpResponse, urlPath, ipAddress, RequestCheckType.IP)){
            return;
        }
        String sessionId = accessKey.getSessionId();
        if (checkThreshold(httpResponse, urlPath, sessionId, RequestCheckType.SESSION)){
            return;
        }
        chain.doFilter(request, response);
    }

    private boolean checkThreshold(HttpServletResponse httpResponse, String urlPath,
                                   String key, RequestCheckType requestCheckType) throws IOException {
        String redisCacheKey = wrapKey(key,requestCheckType);
        int limitCount = limitCount(requestCheckType);

        Long reqCount = yhaoCache.incr(WebCommonCacheKey.CACHE_VISIT_LIMIT, redisCacheKey);
        if (reqCount <= 1) {
            yhaoCache.expire(WebCommonCacheKey.CACHE_VISIT_LIMIT, redisCacheKey, throttlingInterval);
        }
        if (reqCount > limitCount) {
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
            logger.warn(new StringBuffer("来自").append(requestCheckType.name())
                    .append("[").append(key).append("]的请求被拦截,")
                    .append(throttlingInterval).append("秒内次数[").append(reqCount)
                    .append("],请求url[").append(urlPath).append("]")
                    .toString());
            return true;
        }
        return false;
    }

    private int limitCount(RequestCheckType requestCheckType){
        int limitCount = 5;
        switch (requestCheckType){
            case SESSION:
                limitCount = maxAccessCountPerSession;
                break;
            case IP:
                limitCount = maxAccessCountPerIP;
                break;
        }
        return limitCount;
    }

    private String wrapKey(String key,RequestCheckType requestCheckType){
        String cacheKey = null;
        switch (requestCheckType){
            case SESSION:
                cacheKey = SESSION_CACHE_PREFIX + key;
                break;
            case IP:
                cacheKey = IP_CACHE_PREFIX + key;
                break;
        }
        return cacheKey;
    }

    private enum RequestCheckType{
        SESSION,IP
    }

    private AccessKey getAccessKey(HttpServletRequest httpRequest) {
        String sid = (String)httpRequest.getAttribute(WebCommonConstants.REQUEST_SESSION_ID);
        if(StringUtils.isEmpty(sid)){
            throw new RuntimeException("使用AccessThresholdFilter需要配置WebSessionFilter");
        }
        return new AccessKey(CommonWebUtil.getIpAddr(httpRequest)[0], sid);
    }


    private class AccessKey {
        private String remoteAddr;
        private String sessionId;

        private AccessKey(String remoteAddr, String sessionId) {
            super();
            this.remoteAddr = remoteAddr;
            this.sessionId = sessionId;
        }

        public String getRemoteAddr() {
            return remoteAddr;
        }

        public String getSessionId() {
            return sessionId;
        }

        public String toString() {
            if (StringUtils.isEmpty(sessionId)) {
                return remoteAddr;
            } else {
                return remoteAddr + "." + sessionId;
            }
        }
    }

    @Override
    public void destroy() {

    }
}
